package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Api(tags = "C端用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信登录：{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌（accessToken）
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        // 生成refreshToken，过期时间更长
        String refreshToken = JwtUtil.createJWT(
                jwtProperties.getUserRefreshSecretKey(),
                jwtProperties.getUserRefreshTtl(),
                claims);

        // 返回VO对象，包含accessToken和refreshToken
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .refreshToken(refreshToken)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 用refreshToken换取新的accessToken
     * @param refreshToken 前端传递的refreshToken
     * @return 新的accessToken和refreshToken
     */
    @PostMapping("/refresh")
    @ApiOperation("刷新accessToken")
    public Result<UserLoginVO> refreshToken(@RequestBody Map<String, String> body) {
        String refreshToken = body.get("refreshToken");
        try {
            // 校验refreshToken有效性
            io.jsonwebtoken.Claims claims = JwtUtil.parseJWT(jwtProperties.getUserRefreshSecretKey(), refreshToken);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            // 重新生成accessToken
            Map<String, Object> newClaims = new HashMap<>();
            newClaims.put(JwtClaimsConstant.USER_ID, userId);
            String newToken = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    newClaims);
            // refreshToken也可以选择重新签发（滑动过期），这里演示重新签发
            String newRefreshToken = JwtUtil.createJWT(
                    jwtProperties.getUserRefreshSecretKey(),
                    jwtProperties.getUserRefreshTtl(),
                    newClaims);
            UserLoginVO vo = UserLoginVO.builder()
                    .id(userId)
                    .token(newToken)
                    .refreshToken(newRefreshToken)
                    .build();
            return Result.success(vo);
        } catch (Exception e) {
            // refreshToken无效或过期
            return Result.error("refreshToken无效或已过期，请重新登录");
        }
    }
}
